package view;

import com.qoppa.pdfWriter.PDFDocument;
import com.qoppa.pdfWriter.PDFPage;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import main.BarApplication;
import model.Member;
import model.Product;

public class Payment extends JPanel implements MouseListener, ActionListener, KeyListener {

    private final int verticalPosition = 80;
    private final int productOffset = 20;
    private final int formOffset = 30;
    private JTextField tfBirthday;
    private JTextField tfFirstname;
    private JTextField tfMembernumber;
    private JTextField tfLastname;
    private JComboBox cmbPayMethod;
    private JTextField tfNote;
    private JButton btnSend, btnSend2;
    private JLabel lblTitle1;
    private JButton lblTitle2, lblTitle3;
    private KeyboardDisplay keyboard;
    private DecimalFormat df = new DecimalFormat("#0.00");
    private Boolean cursus = false;
    private int cursusId = 0;
    private final String[] payMethods = {"Op rekening", "Contant"};
    private int idVestiging;
    private LoginScreen login;

    public Payment(LoginScreen login, int vestigingId) {
        super();
        this.setLayout(null);
        initComponents();
        this.idVestiging = vestigingId;
        this.login =login;
    }

    private void initComponents() {
        this.setBackground(Color.white);
        addTitle();
        addProductList();
        addForm();
        addKeyboard();

    }

    private void addTitle() {

        lblTitle2 = new JButton();
        lblTitle2.setText("(vorige)");
        lblTitle2.setBounds(300, 20, 150, 20);
        lblTitle2.setFont(BarApplication.FONT_10_BOLD);
        lblTitle2.setName("vorige");
        lblTitle2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        lblTitle2.addActionListener(this);
        this.add(lblTitle2);    

        lblTitle3 = new JButton();
        lblTitle3.setText("(nieuw)");
        lblTitle3.setBounds(450, 20, 150, 20);
        lblTitle3.setFont(BarApplication.FONT_10_BOLD);
        lblTitle3.setName("nieuw");
        lblTitle3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        lblTitle3.addActionListener(this);
        this.add(lblTitle3);
    }

    private void addProductList() {
        List<Product> products = BarApplication.getBasket().getProducts();

        JLabel lblProductHeader = new JLabel();
        lblProductHeader.setText("Producten");
        lblProductHeader.setBounds(20, 60, 150, 20);
        lblProductHeader.setFont(BarApplication.FONT_10_BOLD);
        add(lblProductHeader);

        JLabel lblAmountHeader = new JLabel();
        lblAmountHeader.setText("Aantal");
        lblAmountHeader.setBounds(400, 60, 150, 20);
        lblAmountHeader.setFont(BarApplication.FONT_10_BOLD);
        add(lblAmountHeader);

        JLabel lblPriceHeader = new JLabel();
        lblPriceHeader.setText("Prijs");
        lblPriceHeader.setBounds(480, 60, 150, 20);
        lblPriceHeader.setFont(BarApplication.FONT_10_BOLD);
        add(lblPriceHeader);

        for (int i = 0; i < products.size(); i++) {
            Product product = products.get(i);
            
            if (product.getProductId() > 56){
                cursus = true;
            }
            JLabel lblProduct = new JLabel(product.getName());
            lblProduct.setBounds(20, verticalPosition + i * productOffset, 420, 20);
            lblProduct.setFont(BarApplication.FONT_10_PLAIN);
            add(lblProduct);

            JLabel lblAmount = new JLabel(String.valueOf(BarApplication.getBasket().getProductAmount(product)));
            lblAmount.setBounds(410, verticalPosition + i * productOffset, 70, 20);
            lblAmount.setFont(BarApplication.FONT_10_PLAIN);
            add(lblAmount);

            JLabel lblPrice = new JLabel(BarApplication.CURRENCY + df.format(product.getPrice()));
            lblPrice.setBounds(480, verticalPosition + i * productOffset, 70, 20);
            lblPrice.setFont(BarApplication.FONT_10_PLAIN);
            add(lblPrice);
        }

        // create total labelsve
        JLabel lblTotal = new JLabel("Totaal: ");
        lblTotal.setBounds(20, verticalPosition + products.size() * productOffset, 50, 20);
        lblTotal.setFont(BarApplication.FONT_10_BOLD);
        add(lblTotal);

        // create total labels
        JLabel lblTotalPrice = new JLabel(BarApplication.CURRENCY + df.format(BarApplication.getBasket().getTotalCosts()));
        lblTotalPrice.setBounds(480, verticalPosition + products.size() * productOffset, 70, 20);
        lblTotalPrice.setFont(BarApplication.FONT_10_BOLD);
        add(lblTotalPrice);
    }

    private void addForm() {
        List<Product> products = BarApplication.getBasket().getProducts();
        JLabel lblFormTitle = new JLabel("Gegevens lid:");
        lblFormTitle.setBounds(20, verticalPosition + products.size() * productOffset + (formOffset * 2), 150, 20);
        lblFormTitle.setFont(BarApplication.FONT_12_BOLD);
        add(lblFormTitle);

        JLabel lblMembernumber = new JLabel("Lidnummer:");
        lblMembernumber.setBounds(20, verticalPosition + products.size() * productOffset + (formOffset * 3), 100, 20);
        lblMembernumber.setFont(BarApplication.FONT_10_BOLD);
        add(lblMembernumber);

        tfMembernumber = new JTextField();
        tfMembernumber.setBounds(120, verticalPosition + products.size() * productOffset + (formOffset * 3), 44, 20);
        tfMembernumber.setFont(BarApplication.FONT_10_BOLD);
        tfMembernumber.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {
                // text was changed                
            }

            public void removeUpdate(DocumentEvent e) {
                // text was deleted
            }

            public void insertUpdate(DocumentEvent e) {


                String lidnummer = tfMembernumber.getText();
                int memberId = Integer.parseInt(lidnummer);
                System.out.println("memberId:" + memberId);
                if (memberId != 0) {
                    Member member = BarApplication.getQueryManager().getMember(memberId);
                    if (!(member == null)) {
                        System.out.println(member.getBirthday().toString());

                        //          DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
                        tfBirthday.setText(member.getBirthday());
                        tfFirstname.setText(member.getFirstname());
                        tfLastname.setText(member.getLastname());
                    }
                } else {
                    tfBirthday.setText("Contant");
                    tfFirstname.setText("Contant");
                    tfLastname.setText("Contant");
                }

            }
        });
        add(tfMembernumber);

        JLabel lblBirthday = new JLabel("Geboortedatum:");
        lblBirthday.setBounds(320, verticalPosition + products.size() * productOffset + (formOffset * 3), 100, 20);
        lblBirthday.setFont(BarApplication.FONT_10_BOLD);
        add(lblBirthday);

        tfBirthday = new JTextField();
        tfBirthday.setBounds(420, verticalPosition + products.size() * productOffset + (formOffset * 3), 130, 20);
        tfBirthday.setFont(BarApplication.FONT_10_BOLD);
        tfBirthday.setEnabled(false);
        add(tfBirthday);

        JLabel lblFirstname = new JLabel("Voornaam:");
        lblFirstname.setBounds(20, verticalPosition + products.size() * productOffset + (formOffset * 4), 100, 20);
        lblFirstname.setFont(BarApplication.FONT_10_BOLD);
        add(lblFirstname);

        tfFirstname = new JTextField();
        tfFirstname.setBounds(120, verticalPosition + products.size() * productOffset + (formOffset * 4), 130, 20);
        tfFirstname.setFont(BarApplication.FONT_10_BOLD);
        tfFirstname.setEnabled(false);
        add(tfFirstname);

        JLabel lblLastname = new JLabel("Achternaam:");
        lblLastname.setBounds(320, verticalPosition + products.size() * productOffset + (formOffset * 4), 100, 20);
        lblLastname.setFont(BarApplication.FONT_10_BOLD);
        add(lblLastname);

        tfLastname = new JTextField();
        tfLastname.setBounds(420, verticalPosition + products.size() * productOffset + (formOffset * 4), 130, 20);
        tfLastname.setFont(BarApplication.FONT_10_BOLD);
        tfLastname.setEnabled(false);
        add(tfLastname);

        JLabel lblPayMethod = new JLabel("Betaalmethode:");
        lblPayMethod.setBounds(20, verticalPosition + products.size() * productOffset + (formOffset * 5), 100, 20);
        lblPayMethod.setFont(BarApplication.FONT_10_BOLD);
        add(lblPayMethod);

        cmbPayMethod = new JComboBox(payMethods);
        cmbPayMethod.setBounds(120, verticalPosition + products.size() * productOffset + (formOffset * 5), 250, 20);
        cmbPayMethod.setFont(BarApplication.FONT_10_BOLD);
        cmbPayMethod.setName("dropdown");
        cmbPayMethod.addActionListener(this);
        add(cmbPayMethod);

        JLabel lblNote = new JLabel("Opmerking:");
        lblNote.setBounds(20, verticalPosition + products.size() * productOffset + (formOffset * 6), 100, 20);
        lblNote.setFont(BarApplication.FONT_10_BOLD);
        add(lblNote);

        tfNote = new JTextField();
        tfNote.setBounds(120, verticalPosition + products.size() * productOffset + (formOffset * 6), 250, 80);
        tfNote.setFont(BarApplication.FONT_10_BOLD);
        add(tfNote);

        btnSend = new JButton("Betaal bestelling");
        btnSend.setBounds(120, verticalPosition + products.size() * productOffset + (formOffset * 9), 150, 20);
        btnSend.setFont(BarApplication.FONT_10_BOLD);
        btnSend.setName("betalen");
        btnSend.addActionListener(this);
        this.add(btnSend);

        btnSend2 = new JButton("Betaal bestelling & print bon");
        btnSend2.setBounds(280, verticalPosition + products.size() * productOffset + (formOffset * 9), 230, 20);
        btnSend2.setFont(BarApplication.FONT_10_BOLD);
        btnSend2.setName("betalenPrinten");
        btnSend2.addActionListener(this);
        this.add(btnSend2);


    }

    private void addKeyboard() {
        keyboard = new KeyboardDisplay(tfMembernumber);
        add(keyboard);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        System.out.println(event.getSource().toString());
        if (event.getSource().toString().contains("dropdown")) {
            String check2 = cmbPayMethod.getSelectedItem().toString();

            if ("".equals(tfLastname.getText()) && cursus && check2.equals("Contant")) {
                JOptionPane.showMessageDialog(null, "Vul a.u.b een geldig lidnummer in!");
                cmbPayMethod.setSelectedIndex(0);
                
            }else if(!"".equals(tfLastname.getText()) && cursus && check2.equals("Contant")){
 
            } else {
                tfMembernumber.setText("0");
            }
        } else if (event.getSource().toString().contains("vorige")) {
            BarApplication.getInstance().showPanel(new view.shopping_bar(login));
        } else if (event.getSource().toString().contains("nieuw")) {
            BarApplication.getBasket().empty();
            BarApplication.getInstance().showPanel(new view.shopping_bar(login));
        } else if (tfLastname.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Geen geldig lidnummer !.");
        } else if (event.getSource().toString().contains("betalenPrinten")) {

            try {
                lblTitle2.setVisible(true);
                lblTitle3.setVisible(true);
                tfFirstname.setEnabled(true);
                tfLastname.setEnabled(true);
                tfBirthday.setEnabled(true);
                keyboard.setVisible(false);

                PDFDocument pdfDoc = new PDFDocument();
                PDFPage page = pdfDoc.createPage(null);
                Graphics2D g2d = page.createGraphics();
                btnSend.setVisible(false);
                btnSend2.setVisible(false);
                this.print(g2d);
                pdfDoc.addPage(page);
                pdfDoc.saveDocument("fitshape.pdf");
            } catch (IOException ioe) {

                ioe.printStackTrace();
            }

            List<Product> products = BarApplication.getBasket().getProducts();
            for (int i = 0; i < products.size(); i++) {
            Product product = products.get(i);
            if (product.getCategorieId() == 8 ){  //////////////////////////////////////////////
                cursusId = product.getProductId();
               try{
                BarApplication.getQueryManager().updateCursus(cursusId);
                } catch (Exception e) {
                e.printStackTrace();
            }
            }
           
        }
            
            
            
            int memberId = Integer.parseInt(tfMembernumber.getText());
            String opmerking = tfNote.getText();
            String betaalmethode =  cmbPayMethod.getSelectedItem().toString();
            BarApplication.getQueryManager().setOrder(BarApplication.getBasket(), memberId, opmerking, betaalmethode,idVestiging);
            BarApplication.getBasket().empty();
            BarApplication.getInstance().showPanel(new view.shopping_bar(login));
        } else if (event.getSource().toString().contains("betalen")) {
                        List<Product> products = BarApplication.getBasket().getProducts();
            for (int i = 0; i < products.size(); i++) {
                Product product = products.get(i);
                if (product.getCategorieId() == 8) {
                    cursusId = product.getProductId();
                    try {
                        BarApplication.getQueryManager().updateCursus(cursusId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
            String lidnummer = tfMembernumber.getText();
            int memberId = Integer.parseInt(lidnummer);
            String opmerking = tfNote.getText();
            String betaalmethode = (String) cmbPayMethod.getSelectedItem();
            BarApplication.getQueryManager().setOrder(BarApplication.getBasket(), memberId, opmerking, betaalmethode,idVestiging);
            BarApplication.getBasket().empty();
            BarApplication.getInstance().showPanel(new view.shopping_bar(login));
        }
    }

    @Override
    public void keyReleased(KeyEvent keyEvent) {
        printIt("Released", keyEvent);
    }

    @Override
    public void keyTyped(KeyEvent keyEvent) {
        printIt("Typed", keyEvent);
    }

    @Override
    public void keyPressed(KeyEvent keyEvent) {
        printIt("Pressed", keyEvent);
    }

    private void printIt(String title, KeyEvent keyEvent) {
        int keyCode = keyEvent.getKeyCode();
        String keyText = KeyEvent.getKeyText(keyCode);
        System.out.println(title + " : " + keyText);
    }

    @Override
    public void mouseClicked(MouseEvent event) {
 /*       JLabel label = (JLabel) event.getSource();
        if (label.getName().equals("-1")) {
            // the user clicked on title 1
        } else if (label.getName().equals("-2")) {
            // the user clicked on title 2
            BarApplication.getInstance().showPanel(new view.shopping_bar());
        } else if (label.getName().equals("-3")) {
            // the user clicked on title 3
            BarApplication.getBasket().empty();
            BarApplication.getInstance().showPanel(new view.shopping_bar());
        }
        */
    }

    @Override
    public void mouseEntered(MouseEvent event) {
        // Intentionally left blank.
    }

    @Override
    public void mousePressed(MouseEvent event) {
        // Intentionally left blank.
    }

    @Override
    public void mouseReleased(MouseEvent event) {
        // Intentionally left blank.
    }

    @Override
    public void mouseExited(MouseEvent event) {
        // Intentionally left blank.
    }

    @Override
    public void paint(Graphics graphics) {
        super.paint(graphics);
        graphics.drawLine(20, 45, 540, 45);		// under H Title
    }
}
